﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BLL;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;
using System.Text.RegularExpressions;
using Models;
using System.Collections;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using WeChat.Common;
using WeChat.Common2;
using WeChat.JsSDK.lib;
using WeChat.HyfPay.Hyflib;
using System.Web.SessionState;
using System.IO;
using System.Drawing;
using System.Threading;
using System.Text;
using WeChat.HTTP_Helper;

namespace WeChat
{
    /// <summary>
    /// MenuReserveHandler 的摘要说明
    /// </summary>
    public class MenuReserveHandler : IHttpHandler, IRequiresSessionState
    {
        private object Order_judgment = new object();
        private object Order_payment = new object();
        private string openId;
        public void ProcessRequest(HttpContext context)
        {
            openId = context.Session["openid"].ToString();
            string rtnJson = "";
            MenuReservationBLL mb = new MenuReservationBLL();
            MenuList m = new MenuList();
            JObject jt = new JObject();
            string funcName = context.Request.Form["funcName"];
            switch (funcName)
            {
                case "getall":
                    rtnJson = JsonConvert.SerializeObject(mb.getall());
                    break;

                case "getCState":

                    string OrderId = context.Request.Form["OrderId"];
                    rtnJson = JsonConvert.SerializeObject(mb.getCState(OrderId));
                    break;


                case "Notorder"://不可预定
                    DataRowCollection drc = mb.Notorder().Rows;
                    Hashtable ht = new Hashtable();
                    for (int i = 0; i < drc.Count; i++)
                    {
                        string strKey = Convert.ToDateTime(drc[i]["notorderDate"]).ToShortDateString();
                        string strValue = drc[i]["remark"].ToString();
                        ht.Add(strKey, strValue);

                    }
                    rtnJson = JsonConvert.SerializeObject(mb.Notorder());
                    break;
                case "getTimeState":
                    string sdmc = context.Request.Form["sdmc"];
                    string canteenss = context.Request.Form["canteen"] == null ? "" : context.Request.Form["canteen"].ToString();
                    string openid = context.Request.Form["openid"] == null ? "" : context.Request.Form["openid"].ToString();
                    DataSet df = mb.getTimeState(sdmc, openid, canteenss);
                    rtnJson = JsonConvert.SerializeObject(df.Tables[0]);
                    break;
                case "meulimitnum":
                    rtnJson = "false";
                    sdmc = context.Request.Form["sdmc"];
                    openid = context.Request.Form["openid"];
                    string onsaleid = context.Request.Form["onsaleid"];
                    string jianBtn = context.Request.Form["jianBtn"] == null ? "" : context.Request.Form["jianBtn"];
                    string seldate_dummy = context.Request.Form["seldate_dummy"];
                    string canteen = context.Request.Form["canteen"] == null ? "" : context.Request.Form["canteen"];
                    int number = 1;
                    //解析购物车当前点菜品列表
                    var meunumberlist = (JArray)JsonConvert.DeserializeObject(context.Request["meunumberlist"]);


                    if (canteen == "超市")
                    {
                        foreach (var item in meunumberlist)//如果有项目商品+1
                        {
                            if (onsaleid == item["onsaleid"].ToString())
                            {
                                number++;
                            }
                        }

                        var meunumber = Convert.ToInt32(mb.MeunumberCount(onsaleid).Rows[0]["MeuNumber"]);//按上架id查询剩余份数
                        int meuconsumnumber = number;//获取到当前用户点餐商品份数
                        if (meunumber >= meuconsumnumber)
                        {
                            rtnJson = "true";
                        }
                        ApplicationLog.Write("openid" + openid + "meunumber：" + meunumber + "meuconsumnumber:" + meuconsumnumber + "number:" + number + "rtnJson:" + rtnJson);
                    }
                    else if (canteen != "超市" && canteen != "")
                    {
                        foreach (var item in meunumberlist)//如果有项目商品+1
                        {
                            if (onsaleid == item["onsaleid"].ToString())
                            {
                                number++;
                            }
                            else if (item["onsaleid"].ToString() != "")
                            {
                                number++;
                            }
                        }

                        if (sdmc == "早餐")
                        {
                            sdmc = "1";
                        }
                        else if (sdmc == "午餐" || sdmc == "中餐")
                        {
                            sdmc = "2";
                        }
                        else if (sdmc == "晚餐")
                        {
                            sdmc = "3";
                        }

                        //查询是否当前时段餐次有购买过
                        int Counts = Convert.ToInt32(mb.getcount(seldate_dummy, canteen, sdmc, openid).ToString());
                        var meunumber = Convert.ToInt32(mb.MeunumberCount01(onsaleid).Rows[0]["MeuNumber"]);//按上架id查询剩余份数
                        int meuconsumnumber = number + Counts;//获取到当前用户点餐商品份数
                        int limitation_Number = Convert.ToInt32(ConfigurationSettings.AppSettings["limitation_Number"]);
                        //if (meunumber >= meuconsumnumber && meuconsumnumber == 1)
                        if (meunumber >= meuconsumnumber && limitation_Number >= meuconsumnumber)
                        {
                            rtnJson = "true";
                        }
                        ApplicationLog.Write("openid" + openid + "meunumber：" + meunumber + "meuconsumnumber:" + meuconsumnumber + ",limitation_Number:" + limitation_Number + "number:" + number + "rtnJson:" + rtnJson);
                    }
                    else
                    {

                    }


                    break;

                case "meulimitnumorder":

                    rtnJson = "true";
                    string orderid = context.Request.Form["orderid"];
                    openid = context.Request.Form["openid"];
                    seldate_dummy = context.Request.Form["seldate_dummy"];
                    canteen = context.Request.Form["canteen"] == null ? "" : context.Request.Form["canteen"];
                    //添加线程请求
                    Thread thread = new Thread(() =>
                          {
                              lock (Order_judgment)
                              {
                                  Thread.Sleep(300);
                                      //解析购物车当前点菜品列表
                                      var meuListorder = mb.MeuListOrder(orderid);
                                  var orderNum = 0;
                                  foreach (DataRow item in meuListorder.Rows)
                                  {
                                          orderNum += Convert.ToInt32(item["orderNum"]);//订餐份数
                                          seldate_dummy = item["reservationdate"].ToString();//订餐份数
                                          var onid = item["OnSaleId"].ToString();
                                      if (canteen == "超市")
                                      {
                                          var meunumber = Convert.ToInt32(item["Inventories"]);//剩余份数
                                          if (!(meunumber >= orderNum))
                                          {
                                              rtnJson = "false";
                                              break;
                                          }
                                      }
                                      else if (canteen != "超市")
                                      {
                                          //查询是否当前时段餐次有购买过
                                          int Counts = Convert.ToInt32(mb.getcount01(seldate_dummy, canteen, onid, openid).ToString());
                                          int limitation_Number = Convert.ToInt32(ConfigurationSettings.AppSettings["limitation_Number"]);
                                          orderNum = orderNum + Counts;
                                          var meunumber = Convert.ToInt32(item["ShelvesNum"]);//剩余份数
                                          if (!(meunumber >= orderNum && limitation_Number >= orderNum))
                                          {
                                              rtnJson = "false";
                                              break;
                                          }
                                      }
                                  }
                              }
                          });
                    thread.Start();
                    thread.Join();
                    break;

                case "getMenuList"://菜单列表
                    string TimeStateId = getTimeState(context.Request.Form["TimeState"]);
                    string rq = context.Request.Form["rr"];
                    canteen = context.Request.Form["canteen"] == null ? "" : context.Request.Form["canteen"];
                    string FoodCategoryId = context.Request.Form["FoodCategoryId"] == null ? "" : context.Request.Form["FoodCategoryId"];
                    string Trade_name = context.Request.Form["Trade_name"] == null ? "" : context.Request.Form["Trade_name"];
                    JObject jo = new JObject();
                    jo.Add("baseInfo", JsonConvert.SerializeObject(mb.getMenuList(TimeStateId, rq, canteen, FoodCategoryId, Trade_name)));
                    rtnJson = jo.ToString();
                    break;

                case "getCanteen"://菜单列表 
                    jo = new JObject();
                    var openid_canteen = context.Request.Form["openid"];
                    DataSet ds = mb.getCanteen(openid_canteen);
                    jo.Add("baseInfo", JsonConvert.SerializeObject(ds.Tables[0]));
                    jo.Add("baseInfos", JsonConvert.SerializeObject(ds.Tables[1]));
                    rtnJson = jo.ToString();
                    break;

                case "getFoodCategoryTwo"://获取菜品分类

                    openid_canteen = context.Request.Form["canteen"] == null ? "食堂" : context.Request.Form["canteen"];
                    ds = mb.getFoodCategoryTwo(openid_canteen);
                    JObject jn = new JObject();
                    jn.Add("rows", JsonConvert.SerializeObject(ds.Tables[0]));
                    rtnJson = jn.ToString();
                    break;

                case "getcbReservation"://按餐就餐菜单列表
                    rtnJson = JsonConvert.SerializeObject(mb.getcbReservation());

                    break;
                case "getOrderList"://订单表
                    string ryids = mb.getryid(openId).Rows[0][0].ToString();
                    string State = getState(context.Request.Form["State"]);
                    string types = context.Request.Form["type"];
                    string start = context.Request.Form["start"];
                    string end = context.Request.Form["end"];

                    rtnJson = JsonConvert.SerializeObject(mb.getOrderList(State, ryids, types));
                    break;
                case "getGuid"://得到订单号
                    rtnJson = GuidToLongID();
                    break;
                case "getMenuName":
                    string name = context.Request.Form["name"];
                    rtnJson = JsonConvert.SerializeObject(mb.getMenuName(name));
                    break;
                case "getStateID":
                    string Mname = context.Request.Form["name"];
                    rtnJson = JsonConvert.SerializeObject(mb.getStateID(Mname));
                    break;



                case "AddOrderDetail"://加入订单详情列表
                    string list = context.Request.Form["json"];
                    JObject json = JObject.Parse(list);
                    string oederId = context.Request.Form["OrderId"];
                    string type = context.Request.Form["type"];
                    string reservationdate = context.Request.Form["date"];

                    foreach (var x in json)
                    {
                        string key = x.Key;
                        string velue = x.Value.ToString();
                        OrderDetail od = new OrderDetail();
                        od.OrderId = oederId;
                        if (type == "day")
                        {
                            od.OnSaleId = "0";
                            od.OrderNum = velue;
                            od.reservationdate = key;
                        }
                        else
                        {
                            od.OnSaleId = key;
                            od.OrderNum = velue;
                            od.reservationdate = reservationdate;
                            od.canteen = "";
                        }


                        mb.AddOrderDetail(od);
                    }
                    break;
                case "AddOrderList"://加入订单列表
                    try
                    {


                        string ryid = mb.getryid(context.Request.Form["openid"]).Rows[0][0].ToString();
                        string totalPrice = context.Request.Form["totalPrice"];
                        string oeder = context.Request.Form["OrderId"];
                        string state = context.Request.Form["state"];
                        OrderList ol = new OrderList();
                        ol.OrderId = oeder;
                        ol.Ryid = ryid;
                        ol.TotalPrice = totalPrice;
                        ol.State = state;
                        ol.OrderTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
                        //   ol.PayTime = null;
                        if (ol.State == "2")
                        {
                            ol.payType = "卡内余额";
                        }
                        else
                        {
                            ol.payType = "";
                        }
                        mb.AddOrderList(ol);
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.Write("AddOrderList添加失败：" + ex.Message);
                    }
                    break;


                case "AddOrderDetail_AllIn":

                    list = context.Request.Form["json"];
                    json = JObject.Parse(list);
                    oederId = context.Request.Form["OrderId"];
                    type = context.Request.Form["type"];
                    reservationdate = context.Request.Form["date"];
                    canteen = context.Request.Form["canteen"];
                    foreach (var x in json)
                    {
                        string key = x.Key;
                        string velue = x.Value.ToString();
                        OrderDetail od = new OrderDetail();
                        od.OrderId = oederId;
                        if (type == "day")
                        {
                            od.OnSaleId = "0";
                            od.OrderNum = velue;
                            od.reservationdate = key;
                            od.canteen = canteen;
                        }
                        else
                        {
                            od.OnSaleId = key;
                            od.OrderNum = velue;
                            od.reservationdate = reservationdate;
                            od.canteen = canteen;
                        }


                        mb.AddOrderDetail(od);
                    }

                    try
                    {


                        string ryid = mb.getryid(context.Request.Form["openid"]).Rows[0][0].ToString();
                        string totalPrice = context.Request.Form["totalPrice"];
                        string oeder = context.Request.Form["OrderId"];
                        string state = context.Request.Form["state"];
                        OrderList ol = new OrderList();
                        ol.OrderId = oeder;
                        ol.Ryid = ryid;
                        ol.TotalPrice = totalPrice;
                        ol.State = state;
                        ol.OrderTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
                        //   ol.PayTime = null;
                        if (ol.State == "2")
                        {
                            ol.payType = "卡内余额";
                        }
                        else
                        {
                            ol.payType = "";
                        }
                        mb.AddOrderList(ol);
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.Write("AddOrderList添加失败：" + ex.Message);
                    }




                    break;





                case "getdatatime"://得到预定日期
                    int reservationdays = Convert.ToInt32(context.Request.Form["reservationdays"]);
                    List<string> myList = new List<string>();
                    for (int i = 0; i < reservationdays; i++)
                    {
                        string datatimes = DateTime.Now.AddDays(i).ToShortDateString();
                        myList.Add(datatimes);
                    }
                    rtnJson = JsonConvert.SerializeObject(myList);
                    break;
                case "yePay"://余额支付

                    string oederIds = context.Request.Form["OrderId"];
                    string price = context.Request.Form["price"];
                    openid = context.Request.Form["openid"];
                    string address = context.Request.Form["address"];
                    string address2 = context.Request.Form["address2"] == null ? "" : context.Request.Form["address2"];
                    string telnum = context.Request.Form["telnum"];
                    string jfzt = context.Request.Form["jfzt"] == null ? "" : context.Request.Form["jfzt"];
                    canteen = context.Request.Form["canteen"];
                    ApplicationLog.Write("电话：" + telnum + ",地址：" + address + ",jfzt:" + jfzt);

                    Thread thread1 = new Thread(() =>
                    {
                        lock (Order_payment)
                        {
                            Thread.Sleep(300);
                            int p1 = 0;
                            try
                            {
                                p1 = MenuReservationBLL.updateryxx(oederIds, price, jfzt);
                                ApplicationLog.Write(Convert.ToString(p1));


                                //同步扣款

                                //获取卡号、用户编号	
                                DataTable dns = MenuReservationBLL.Select_CUST_ID(oederIds);
                                string CUST_ID = dns.Rows[0]["bankcard"].ToString();//CUST_ID
                                string CARD_ID = dns.Rows[0]["rfkh"].ToString();//用户编号	
                                //string ORDER_ID = GenerateOutTradeNos();//随机数生成订单号
                                string ORDER_ID = oederIds.ToString();//随机数生成订单号
                                //设置机器号
                                string device_number = ConfigurationSettings.AppSettings["device_number"] == "" ? "000" : ConfigurationSettings.AppSettings["device_number"].ToString();
                                ApplicationLog.Write("获取到设置机器号：" + device_number);
                                //获取商家编号、柜台编号
                                DataTable BD = MenuReservationBLL.Get_BUSINESS_ID(device_number);
                                string BUSINESS_ID = BD.Rows[0]["MacAddress"].ToString();//商家编号	
                                string VPOS_ID = BD.Rows[0]["xlmc"].ToString();//柜台编号	
                                if (BUSINESS_ID == null || VPOS_ID == null || BUSINESS_ID == "" || VPOS_ID == "")
                                {
                                    ApplicationLog.Write("商家编号为空：" + BUSINESS_ID + ",柜台编号为空:" + VPOS_ID);
                                }
                                else
                                {
                                    ApplicationLog.Write("商家编号：" + BUSINESS_ID + ",柜台编号:" + VPOS_ID);
                                }

                                //同步调用接口消费
                                //获取到修改信息,进行同步
                                string CAMPUS_NAME = ConfigurationSettings.AppSettings["CAMPUS_NAME"];
                                string CAMPUS_ID = ConfigurationSettings.AppSettings["CAMPUS_ID"]; //园区ID		
                                string CORP_ID = ConfigurationSettings.AppSettings["CORP_ID"];     //合作方ID	 
                                string Sign = ConfigurationSettings.AppSettings["ccbSafeParam"];
                                string key_url = ConfigurationSettings.AppSettings["key_url"];//密钥url
                                string Request_Link = ConfigurationSettings.AppSettings["Request_Link"];//请求链接
                                Dictionary<string, string> pairs = new Dictionary<string, string>();
                                pairs.Add("CAMPUS_ID", CAMPUS_ID);
                                pairs.Add("CORP_ID", CORP_ID);
                                pairs.Add("TXCODE", "PAY005");
                                pairs.Add("BUSINESS_ID", BUSINESS_ID);//商家编号		
                                pairs.Add("VPOS_ID", VPOS_ID);//柜台编号		
                                pairs.Add("PAYMENT", price.ToString());//支付金额		
                                pairs.Add("ACTUAL_PAYMENT", price.ToString());//实际支付金额		
                                pairs.Add("OFFLINE", "0");//联机支付	
                                pairs.Add("CARD_ID", CARD_ID);//卡号	
                                pairs.Add("CUST_ID", CUST_ID);//用户编号	
                                pairs.Add("ORDER_ID", ORDER_ID);//订单编号	
                                string Signparam = GetSignContent01(pairs);
                                ApplicationLog.Write("获取到参数：" + Signparam);
                                var context01 = new { key = Sign, data = Signparam };
                                string data = JsonConvert.SerializeObject(context01);
                                ApplicationLog.Write("token_data:" + data);
                                string ccbSafeParams = WebapiHelper.PostWebRequest(key_url, data, "", Encoding.GetEncoding("UTF-8"));
                                Dictionary<object, object> jspay_info_keys = JsonConvert.DeserializeObject<Dictionary<object, object>>(ccbSafeParams);
                                //  ApplicationLog.Write("jspay_info_key:" + jspay_info_keys);
                                string ccbSafeParam = jspay_info_keys["data"].ToString();
                                ApplicationLog.Write("获取到加密密钥：" + ccbSafeParam);

                                Dictionary<string, string> pairs01 = new Dictionary<string, string>();
                                pairs01.Add("CCB_IBSVersion", "V6");
                                pairs01.Add("PT_STYLE", "8");
                                pairs01.Add("PT_LANGUAGE", "CN");
                                pairs01.Add("CAMPUS_ID", CAMPUS_ID);
                                pairs01.Add("CORP_ID", CORP_ID);
                                pairs01.Add("TXCODE", "PAY005");
                                pairs01.Add("BUSINESS_ID", BUSINESS_ID);//商家编号		
                                pairs01.Add("VPOS_ID", VPOS_ID);//柜台编号		
                                pairs01.Add("PAYMENT", price.ToString());//支付金额		
                                pairs01.Add("ACTUAL_PAYMENT", price.ToString());//实际支付金额		
                                pairs01.Add("OFFLINE", "0");//联机支付	
                                pairs01.Add("CARD_ID", CARD_ID);//卡号	
                                pairs01.Add("CUST_ID", CUST_ID);//用户编号	
                                pairs01.Add("ORDER_ID", ORDER_ID);//订单编号	
                                pairs01.Add("ccbSafeParam", ccbSafeParam);

                                string context02 = GetSignContent01(pairs01);
                                ApplicationLog.Write("获取到用户信息请求参数：" + context02);
                                //测试地址：http://121.40.54.232:8090/CCBIS/B2CMainPlat_00_ZHST
                                //生产环境：https://dining.icenter.ccb.com/CCBIS/B2CMainPlat_00_ZHST
                                string Response = WebapiHelper.PostWebRequest(Request_Link + context02, "", "", Encoding.GetEncoding("UTF-8"));
                                //获取回调返回值
                                Dictionary<object, object> jspay_info_key = JsonConvert.DeserializeObject<Dictionary<object, object>>(Response);
                                //  ApplicationLog.Write("jspay_info_key:" + jspay_info_key);
                                //响应结果Y：成功 N：失败	
                                string RESULT = jspay_info_key["RESULT"].ToString();
                                ApplicationLog.Write("RESULT:" + RESULT);
                                string PAYMENT = jspay_info_key["PAYMENT"].ToString();
                                ApplicationLog.Write("PAYMENT:" + PAYMENT);
                                string ACC_NO = jspay_info_key["ACC_NO"].ToString();
                                ApplicationLog.Write("ACC_NO:" + ACC_NO);
                                string ACC_TYPE = jspay_info_key["ACC_TYPE"].ToString();
                                ApplicationLog.Write("ACC_TYPE:" + ACC_TYPE);
                                string ACC_LIST = jspay_info_key["ACC_LIST"].ToString();
                                ApplicationLog.Write("ACC_LIST:" + ACC_LIST);

                            }
                            catch (Exception e)
                            {

                                ApplicationLog.Write("扣款异常信息为：" + e.Message);
                            }

                            if (p1 > 0)
                            {

                                int num = 0;
                                try
                                {
                                    num = mb.updateOrderList(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), "卡内余额", oederIds, address, address2, telnum);
                                    ApplicationLog.Write("返回值num：" + num);
                                }
                                catch (Exception e)
                                {

                                    ApplicationLog.Write("更新订单异常信息为：" + e.Message);
                                }

                                try
                                {
                                    if (num > 0)
                                    {
                                        //解析购物车当前点菜品列表
                                        var Listdetails = mb.MeuListOrder(oederIds);
                                        foreach (DataRow item in Listdetails.Rows)
                                        {
                                            var orderNum = Convert.ToInt32(item["orderNum"]);
                                            var MenuId = item["MenuId"].ToString();
                                            var OnSaleIdm = item["OnSaleId"].ToString();
                                            int Menu = mb.updateMenulist(orderNum, MenuId, OnSaleIdm, canteen);

                                            ApplicationLog.Write("订餐成功后份数扣除：份数：" + orderNum + ",菜品ID：" + MenuId + ",修改状态：" + Menu);

                                        }

                                        if (num > 0 && canteen == "超市")
                                        {

                                            //获取到当前年月日
                                            string Time = DateTime.Now.ToString("HH:mm:ss");
                                            string Counts = mb.GetOrderlist_Count(oederIds, canteen, Time);
                                            Counts = oederIds + "_" + Counts;
                                            ApplicationLog.Write("获取到订餐号Counts：" + Counts);
                                            string mealsNum = mb.Update_Orderlist(oederIds, Counts);

                                        }


                                        rtnJson = "SUCCESS";
                                        //发布时取消注释
                                        //string returnText = Config.setOrderReturn(oederIds, double.Parse(price));
                                        //KefuSendMsg.sendText(openid, returnText);
                                    }
                                }
                                catch (Exception e)
                                {
                                    ApplicationLog.Write("订单付款后扣除相应份数：" + e.Message);
                                }

                            }
                            else
                            {
                                rtnJson = "fail";
                            }
                        }
                    });


                    thread1.Start();
                    thread1.Join();
                    break;

                case "wxaddress"://微信支付添加地址和电话
                    address = context.Request.Form["address"];
                    address2 = context.Request.Form["address2"] == null ? "" : context.Request.Form["address2"];
                    telnum = context.Request.Form["telnum"];
                    oederIds = context.Request.Form["OrderId"];
                    openid = context.Request.Form["openid"];
                    mb.updateOrderList2("", "", oederIds, address, address2, telnum);

                    break;





                case "getpayType"://得到支付类型
                    OrderId = context.Request.Form["OrderId"];
                    rtnJson = JsonConvert.SerializeObject(mb.getpayType(OrderId));
                    break;
                case "Refund"://余额支付，不扣款,退餐
                    string OR = context.Request.Form["OrderId"];
                    openid = context.Request.Form["openid"] == null ? "" : context.Request.Form["openid"];
                    price = context.Request.Form["TotalPrice"] == null ? "" : context.Request.Form["TotalPrice"];

                    try
                    {

                        var Nums = mb.Refund(OR);
                        if (Nums > 0)
                        {

                            List<StockDto> list01 = new List<StockDto>();
                            DataSet Det = mb.SelAddsdTime(OR);
                            string Numsn = JsonConvert.SerializeObject(Det.Tables[0]);
                            list01 = JsonConvert.DeserializeObject<List<StockDto>>(Numsn);
                            foreach (var item in list01)
                            {
                                StockDto sd = new StockDto();
                                sd.OnSaleId = item.OnSaleId;
                                sd.OrderNum = item.OrderNum;
                                sd.canteen = item.canteen;

                                int Numsq = mb.menulistNum(sd.OnSaleId, Convert.ToInt16(sd.OrderNum), sd.canteen);

                            }

                            string zt = mb.GetZt(OR);
                            if (zt == "00")
                            {
                                zt = "现金账户";
                            }
                            else
                            {
                                zt = "补贴账户";
                            }


                            //获取到修改信息,进行同步
                            string CAMPUS_NAME = ConfigurationSettings.AppSettings["CAMPUS_NAME"];
                            string CAMPUS_ID = ConfigurationSettings.AppSettings["CAMPUS_ID"]; //园区ID		
                            string CORP_ID = ConfigurationSettings.AppSettings["CORP_ID"];     //合作方ID	 
                            string Sign = ConfigurationSettings.AppSettings["ccbSafeParam"];
                            string key_url = ConfigurationSettings.AppSettings["key_url"];//密钥url
                            string Request_Link = ConfigurationSettings.AppSettings["Request_Link"];//请求链接
                            //查询用户用户ID、账户ID
                            DataTable dns = mb.Select_CUST_ID01(OR);
                            string CUST_ID = dns.Rows[0]["bankcard"].ToString();//用户ID
                            string grye = dns.Rows[0]["dz"].ToString();//现金账户ID
                            string btye = dns.Rows[0]["bz"].ToString();//餐补账户ID
                            string moneyss = mb.GetOrderList(OR);
                            Decimal auoumt = 0;
                            auoumt = decimal.Round(Math.Abs(decimal.Parse(moneyss.ToString())), 2);
                            ApplicationLog.Write("获取到群主补贴最终请求金额：" + auoumt);
                            string ORDER_ID = GenerateOutTradeNos();//随机数生成订单号
                            string TRAN_ID = OR;//退款流水号	

                            //同步退款
                            if (zt == "现金账户")
                            {

                                ApplicationLog.Write("进入到现金账户！");
                                Dictionary<string, string> pairs = new Dictionary<string, string>();
                                pairs.Add("CAMPUS_ID", CAMPUS_ID);
                                pairs.Add("CORP_ID", CORP_ID);
                                pairs.Add("TXCODE", "VIAC02");
                                pairs.Add("CUST_ID", CUST_ID);//用户ID		
                                pairs.Add("ACC_NO", grye.ToString());//账户ID		
                                pairs.Add("MONEY", auoumt.ToString());//充值金额		
                                pairs.Add("ORDER_ID", ORDER_ID);//订单号	
                                string Signparam = GetSignContent01(pairs);
                                ApplicationLog.Write("获取到参数：" + Signparam);
                                var context01 = new { key = Sign, data = Signparam };
                                string data = JsonConvert.SerializeObject(context01);
                                ApplicationLog.Write("token_data:" + data);
                                string ccbSafeParams = WebapiHelper.PostWebRequest(key_url, data, "", Encoding.GetEncoding("UTF-8"));
                                Dictionary<object, object> jspay_info_keys = JsonConvert.DeserializeObject<Dictionary<object, object>>(ccbSafeParams);
                                //  ApplicationLog.Write("jspay_info_key:" + jspay_info_keys);
                                string ccbSafeParam = jspay_info_keys["data"].ToString();
                                ApplicationLog.Write("获取到加密密钥：" + ccbSafeParam);
                                Dictionary<string, string> pairs01 = new Dictionary<string, string>();
                                pairs01.Add("CCB_IBSVersion", "V6");
                                pairs01.Add("PT_STYLE", "8");
                                pairs01.Add("PT_LANGUAGE", "CN");
                                pairs01.Add("CAMPUS_ID", CAMPUS_ID);
                                pairs01.Add("CORP_ID", CORP_ID);
                                pairs01.Add("TXCODE", "VIAC02");
                                pairs01.Add("CUST_ID", CUST_ID);//用户ID		
                                pairs01.Add("ACC_NO", grye.ToString());//账户ID		
                                pairs01.Add("MONEY", auoumt.ToString());//充值金额		
                                pairs01.Add("ORDER_ID", ORDER_ID);//订单号	
                                pairs01.Add("ccbSafeParam", ccbSafeParam);
                                string context02 = GetSignContent01(pairs01);
                                ApplicationLog.Write("获取到用户信息请求参数：" + context02);
                                //测试地址：http://121.40.54.232:8090/CCBIS/B2CMainPlat_00_ZHST
                                //生产环境：https://dining.icenter.ccb.com/CCBIS/B2CMainPlat_00_ZHST
                                string Response = WebapiHelper.PostWebRequest(Request_Link + context02, "", "", Encoding.GetEncoding("UTF-8"));
                                //获取回调返回值
                                ApplicationLog.Write("获取值Response：" + Response);
                                Dictionary<object, object> jspay_info_key = JsonConvert.DeserializeObject<Dictionary<object, object>>(Response);
                                //  ApplicationLog.Write("jspay_info_key:" + jspay_info_key);
                                //响应结果Y：成功 N：失败	
                                string RESULT = jspay_info_key["RESULT"].ToString();
                                ApplicationLog.Write("RESULT:" + RESULT);
                                string BALANCE = jspay_info_key["BALANCE"].ToString();
                                ApplicationLog.Write("BALANCE:" + BALANCE);
                                string ORDER_IDS = jspay_info_key["ORDER_ID"].ToString();
                                ApplicationLog.Write("ORDER_ID:" + ORDER_IDS);
                            }
                            else if (zt == "补贴账户")
                            {
                                ApplicationLog.Write("进入到补贴账户！");

                                Dictionary<string, string> pairs = new Dictionary<string, string>();
                                pairs.Add("CAMPUS_ID", CAMPUS_ID);
                                pairs.Add("CORP_ID", CORP_ID);
                                pairs.Add("TXCODE", "VIAC02");
                                pairs.Add("CUST_ID", CUST_ID);//用户ID		
                                pairs.Add("ACC_NO", btye.ToString());//账户ID		
                                pairs.Add("MONEY", auoumt.ToString());//充值金额		
                                pairs.Add("ORDER_ID", ORDER_ID);//订单号	
                                string Signparam = GetSignContent01(pairs);
                                ApplicationLog.Write("获取到参数：" + Signparam);
                                var context01 = new { key = Sign, data = Signparam };
                                string data = JsonConvert.SerializeObject(context01);
                                ApplicationLog.Write("token_data:" + data);
                                string ccbSafeParams = WebapiHelper.PostWebRequest(key_url, data, "", Encoding.GetEncoding("UTF-8"));
                                Dictionary<object, object> jspay_info_keys = JsonConvert.DeserializeObject<Dictionary<object, object>>(ccbSafeParams);
                                //  ApplicationLog.Write("jspay_info_key:" + jspay_info_keys);
                                string ccbSafeParam = jspay_info_keys["data"].ToString();
                                ApplicationLog.Write("获取到加密密钥：" + ccbSafeParam);
                                Dictionary<string, string> pairs01 = new Dictionary<string, string>();
                                pairs01.Add("CCB_IBSVersion", "V6");
                                pairs01.Add("PT_STYLE", "8");
                                pairs01.Add("PT_LANGUAGE", "CN");
                                pairs01.Add("CAMPUS_ID", CAMPUS_ID);
                                pairs01.Add("CORP_ID", CORP_ID);
                                pairs01.Add("TXCODE", "VIAC02");
                                pairs01.Add("CUST_ID", CUST_ID);//用户ID		
                                pairs01.Add("ACC_NO", btye.ToString());//账户ID		
                                pairs01.Add("MONEY", auoumt.ToString());//充值金额		
                                pairs01.Add("ORDER_ID", ORDER_ID);//订单号	
                                pairs01.Add("ccbSafeParam", ccbSafeParam);
                                string context02 = GetSignContent01(pairs01);
                                ApplicationLog.Write("获取到用户信息请求参数：" + context02);
                                //测试地址：http://121.40.54.232:8090/CCBIS/B2CMainPlat_00_ZHST
                                //生产环境：https://dining.icenter.ccb.com/CCBIS/B2CMainPlat_00_ZHST
                                string Response = WebapiHelper.PostWebRequest(Request_Link + context02, "", "", Encoding.GetEncoding("UTF-8"));
                                //获取回调返回值
                                ApplicationLog.Write("获取值Response：" + Response);
                                Dictionary<object, object> jspay_info_key = JsonConvert.DeserializeObject<Dictionary<object, object>>(Response);
                                //  ApplicationLog.Write("jspay_info_key:" + jspay_info_key);
                                //响应结果Y：成功 N：失败	
                                string RESULT = jspay_info_key["RESULT"].ToString();
                                ApplicationLog.Write("RESULT:" + RESULT);
                                string BALANCE = jspay_info_key["BALANCE"].ToString();
                                ApplicationLog.Write("BALANCE:" + BALANCE);
                                string ORDER_IDS = jspay_info_key["ORDER_ID"].ToString();
                                ApplicationLog.Write("ORDER_ID:" + ORDER_IDS);
                            }

                            rtnJson = JsonConvert.SerializeObject(Nums);
                        }


                        //rtnJson = JsonConvert.SerializeObject(mb.Refund(OR));
                    }
                    catch (Exception ex)
                    {

                        ApplicationLog.Write("退款sql语句异常信息为：" + ex.Message);
                    }

                    ////=====退餐提醒=======
                    //string returnText2 = Config.setOrderReturn2(OR, double.Parse(price));
                    //ApplicationLog.Write("返回文本内容为：" + returnText2);
                    //try
                    //{
                    //    ApplicationLog.Write("返回文本内容给的openid：" + openid);
                    //    KefuSendMsg.sendText(openid, returnText2);
                    //}
                    //catch (Exception ex)
                    //{

                    //    ApplicationLog.Write("返回文本接口异常信息为：" + ex.Message);
                    //}
                    break;
                case "WxRefund"://微信支付，退餐，退款
                    string OI = context.Request.Form["OrderId"];
                    string TotalPrice = context.Request.Form["TotalPrice"];
                    WxPayApi.getrefundresult(OI, TotalPrice, TotalPrice);
                    break;



                //case "addaddress"://添加配送地址
                //    OrderId = context.Request.Form["OrderId"];
                //    string address = context.Request.Form["address"];
                //    int a = mb.updateaddress(OrderId, address);

                //    break;

                case "managecantent":
                    string jh = context.Request["jh"] == null ? "001" : context.Request["jh"].Trim();
                    jt.Add("rows", JsonConvert.SerializeObject(BLL.Information_DeliveryBLL.GetCanteen(jh)));
                    rtnJson = jt.ToString();
                    break;


                case "getMyImages":
                    string img = Information_DeliveryBLL.GetImages();
                    img = img.Replace("/images", "");
                    img = "/images" + img;
                    jt.Add("rows", JsonConvert.SerializeObject(img));
                    rtnJson = jt.ToString();
                    break;

                //获取题目
                case "SelTitle_Publish":
                    jh = context.Request["jh"] == null ? "001" : context.Request["jh"].Trim();
                    jt.Add("rows", JsonConvert.SerializeObject(BLL.Information_DeliveryBLL.SelTitle_Publish(jh)));
                    rtnJson = jt.ToString();
                    break;

                //添加问卷调查内容
                case "FindingsAdd":
                    string questionCode = context.Request["questionCode"] == null ? "" : context.Request["questionCode"].Trim();
                    string questionjh = context.Request["questionjh"] == null ? "" : context.Request["questionjh"].Trim();
                    string questionName = context.Request["questionName"] == null ? "" : context.Request["questionName"].Trim();
                    string content = context.Request["content"] == null ? "" : context.Request["content"].Trim();
                    string Investigator = context.Request["Investigator"] == null ? "匿名" : context.Request["Investigator"].Trim();
                    if (questionCode != null && content != null && questionName != null)
                    {
                        string[] Code = questionCode.Split(',');
                        string[] Cont = content.Split(',');
                        string[] Name = questionName.Split(',');
                        var Num = 0;
                        var Content = "";
                        var res = Code.Zip(Cont, (n, w) => new { Number = n, Word = w });

                        foreach (var a in res)
                        {
                            if (a.Number != "" && a.Word != "")
                            {
                                Content = BLL.Information_DeliveryBLL.questionnaire(a.Number);

                                Num += BLL.Information_DeliveryBLL.FindingsAdd(a.Number, questionjh, Content, a.Word, Investigator);
                            }
                        }

                        rtnJson = Num.ToString();

                    }

                    //int num_Add = 0;
                    //num_Add = BLL.Information_DeliveryBLL.FindingsAdd(questionCode, questionjh, content, Investigator);
                    //rtnJson = num_Add.ToString();
                    break;

                case "Increase_Dish_Evaluation":
                    string satisfied = context.Request["satisfied"] == null ? "" : context.Request["satisfied"].Trim();
                    string summary = context.Request["summary"] == null ? "" : context.Request["summary"].Trim();
                    var Numsd = BLL.Information_DeliveryBLL.Increase_Dish_Evaluation(satisfied, summary);
                    rtnJson = Numsd.ToString();
                    break;

                case "Custom_InformationAdd":
                    string text = context.Request["text"] == null ? "" : context.Request["text"].Trim();
                    var request = HttpContext.Current.Request;
                    string dirName = "images";
                    string imageUrl = string.Empty;
                    try
                    {
                        if (request.Files.Count > 0)
                        {
                            foreach (string f in request.Files)
                            {
                                var file = request.Files[f];

                                string fileExtension = Path.GetExtension(file.FileName).ToLower();
                                string dir = "/" + dirName + "/Custom";
                                string dirL = "/" + dirName + "/Custom/images/";
                                string fileName = file.FileName;
                                imageUrl = dirL + fileName;
                                string filePath = HttpContext.Current.Server.MapPath(dir);
                                string filePath1 = HttpContext.Current.Server.MapPath(dirL);
                                if (!Directory.Exists(filePath))
                                {
                                    Directory.CreateDirectory(filePath);
                                }
                                string fileSavePath = Path.Combine(filePath, fileName);
                                string fileSavePath1 = Path.Combine(filePath1, fileName);
                                //判断上传文件是否重名，若重名，则删除原来文件覆盖上传
                                if (File.Exists(fileSavePath))
                                {
                                    File.Delete(fileSavePath);
                                    File.Delete(fileSavePath1);
                                }
                                Stream postStream = file.InputStream;
                                //
                                FileStream fs = new FileStream(fileSavePath, FileMode.Create);
                                byte[] new_b = new byte[1024];
                                const int rbuffer = 1024;

                                while (postStream.Read(new_b, 0, rbuffer) != 0)
                                {
                                    fs.Write(new_b, 0, rbuffer);
                                }
                                postStream.Close();
                                fs.Close();
                                fs.Dispose();
                                MakeThumbnail(fileSavePath, fileSavePath1, 400, 400, "H");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.Write("Custom_InformationAdd:" + ex.Message);
                    }

                    //获取图片名称
                    var images = imageUrl;

                    var Number = BLL.Information_DeliveryBLL.Custom_InformationAdd(text, images);

                    rtnJson = Number.ToString();

                    break;

                //获取信息浏览数据
                case "Custom_Information":
                    jh = context.Request["jh"] == null ? "001" : context.Request["jh"].Trim();
                    jt.Add("rows", JsonConvert.SerializeObject(BLL.Information_DeliveryBLL.GetCustomCode(jh)));
                    rtnJson = jt.ToString();
                    break;

            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(rtnJson);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string getTimeState(string state)
        {
            string rtnState = "1";
            switch (state)
            {
                case "breakfast":
                    rtnState = "1";
                    break;
                case "lunch":
                    rtnState = "2";
                    break;
                case "dinner":
                    rtnState = "3";
                    break;
                case "midnightSnack":
                    rtnState = "4";
                    break;
                case "supermarket":
                    rtnState = "1";
                    break;
                case "all":
                    rtnState = "";
                    break;
            }
            return rtnState;
        }
        public string getState(string state)
        {
            string rtnState = "";
            switch (state)
            {
                case "Topayment":
                    rtnState = "1";
                    break;
                case "Totakefood":
                    rtnState = "2";
                    break;
                case "Havetakefood":
                    rtnState = "3";
                    break;
                case "Toevaluate":
                    rtnState = "4";
                    break;
                case "all":
                    rtnState = "";
                    break;
            }
            return rtnState;
        }

        //年月日时分秒+4位随机数
        public static string GuidToLongID()
        {
            var ran = new Random();
            return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMdd"), ran.Next(99999)).Trim();

        }

        //public static string GuidToLongID()
        //{
        //    byte[] buffer = Guid.NewGuid().ToByteArray();
        //    string guid = BitConverter.ToInt64(buffer, 0).ToString();
        //    string str = new string(guid.Reverse().Take(6).Reverse().ToArray());
        //    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
        //    DateTime nowTime = DateTime.Now;
        //    string unixTime = Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero).ToString();
        //    string strs = new string(unixTime.Reverse().Take(6).Reverse().ToArray());
        //    return str + strs;
        //}
        public class StockDto
        {
            public string OnSaleId { get; set; }
            public string OrderNum { get; set; }
            public string canteen { get; set; }
        }


        public static string GenerateOutTradeNos()
        {
            var ran = new Random();
            return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(9999)).Trim();

        }
        public static string GetSignContent01(IDictionary<string, string> parameters)
        {
            // 第一步：把字典按Key的字母顺序排序
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            sortedParams = (from enty in sortedParams orderby enty.Value ascending select enty).ToDictionary(p => p.Key, p => p.Value);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            // 第二步：把所有参数名和参数值串在一起
            StringBuilder query = new StringBuilder("");
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append("=").Append(value).Append("&");
                    //query.Append(value).Append("&");
                }
            }
            string content = query.ToString().Substring(0, query.Length - 1);

            return content;
        }


        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.White);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
    }
}